package com.youlu.campus.service.platform.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.AIPointPlatformConfig;
import com.youlu.campus.entity.PlatformConfig;
import com.youlu.campus.entity.PointPlatformConfig;
import com.youlu.campus.entity.PointPlatformConfigQueryVO;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.VO.res.CsQQOpenIdRes;
import com.youlu.campus.entity.VO.res.PlatformInfoVO;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.service.platform.PointPlatformConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class PointPlatformConfigServiceImpl implements PointPlatformConfigService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PlatformConfigService platformConfigService;

    @Override
    public PointPlatformConfig findOne(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, PointPlatformConfig.class);
    }

    @Override
    public PointPlatformConfig find(String appId) {
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId));
        return mongoTemplate.findOne(query, PointPlatformConfig.class);
    }


    @Override
    public PointPlatformConfig find() {
        Query query = new Query();
        return mongoTemplate.findOne(query, PointPlatformConfig.class);
    }

    @Override
    public boolean update(PointPlatformConfig req) {
        log.info(":>>> 开始修改积分平台配置:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId())) {
            return false;
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (StringUtils.isNotBlank(req.getCsInfo())) {
            update.set("csInfo", req.getCsInfo());
        }
        if (StringUtils.isNotBlank(req.getDesc())) {
            update.set("desc", req.getDesc());
        }
        if (StringUtils.isNotBlank(req.getPlatform())) {
            update.set("platform", req.getPlatform());
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            update.set("appId", req.getAppId());
        }
        if (StringUtils.isNotBlank(req.getAppName())) {
            update.set("appName", req.getAppName());
        }
        if (Objects.nonNull(req.getRules())) {
            update.set("rules", req.getRules());
        }
        if (Objects.nonNull(req.getTotalPoint())) {
            update.set("totalPoint", req.getTotalPoint());
        }
        if (StringUtils.isNotBlank(req.getPointDetail())) {
            update.set("pointDetail", req.getPointDetail());
        }
        if (StringUtils.isNotBlank(req.getCsQQNumber())) {
            update.set("csQQNumber", req.getCsQQNumber());
        }
        if (StringUtils.isNotBlank(req.getShareTitle())) {
            update.set("shareTitle", req.getShareTitle());
        }
        if (StringUtils.isNotBlank(req.getShareImageUrl())) {
            update.set("shareImageUrl", req.getShareImageUrl());
        }
        if (Objects.nonNull(req.getHasMp())) {
            update.set("hasMp", req.getHasMp());
        }
        if (StringUtils.isNotBlank(req.getCsOpenId())) {
            update.set("csOpenId", req.getCsOpenId());
        }
        if (StringUtils.isNotBlank(req.getCaTips())) {
            update.set("caTips", req.getCaTips());
        }
        if (StringUtils.isNotBlank(req.getCsImageUrl())) {
            update.set("csImageUrl", req.getCsImageUrl());
        }
        return mongoTemplate.updateFirst(query, update, PointPlatformConfig.class).getModifiedCount() > 0 ? true : false;
    }

    @Override
    public Integer getPoint(String bizType) {
        PointPlatformConfig config = find();
        if (Objects.isNull(config)) {
            log.error(":>>> 平台没有配置积分规则");
            return 0;
        }
        if (config.getRules().containsKey(bizType)) {
            return config.getRules().get(bizType);
        }
        return 0;

    }

    @Override
    public Integer getPoint(String appId, String bizType) {
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId));
        PointPlatformConfig config = mongoTemplate.findOne(query, PointPlatformConfig.class);
        if (Objects.isNull(config)) {
            log.error(":>>> 平台没有配置积分规则");
            return 0;
        }
        if (config.getRules().containsKey(bizType)) {
            return config.getRules().get(bizType);
        }
        return 0;
    }

    @Override
    public Page<PointPlatformConfig> list(@NotNull PointPlatformConfigQueryVO req) {
        log.info(":>>> 开始积分平台配置:{}", JSON.toJSONString(req));
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getPlatform())) {
            query.addCriteria(Criteria.where("platform").is(req.getPlatform()));
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            query.addCriteria(Criteria.where("appId").is(req.getAppId()));
        }
        query.addCriteria(Criteria.where("deleted").ne(true));
        long count = mongoTemplate.count(query, PointPlatformConfig.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<PointPlatformConfig> infos = mongoTemplate.find(query.with(pageRequest), PointPlatformConfig.class);
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);
    }

    @Override
    public boolean create(@NotNull PointPlatformConfig req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(@NotNull String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("deleted", true);
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, PointPlatformConfig.class);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public String[] findCsByAppIdAndPlatform(String appId, String platform) {
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId)).addCriteria(Criteria.where("platform").is(platform));
        PointPlatformConfig pointPlatformConfig = this.mongoTemplate.findOne(query, PointPlatformConfig.class);
        if (Objects.nonNull(pointPlatformConfig)) {
            String csQQNumber = pointPlatformConfig.getCsQQNumber();
            if (StringUtils.isNotBlank(csQQNumber)) {
                return csQQNumber.split(",");
            }
        }
        return new String[]{};
    }

    @Override
    public CsQQOpenIdRes findCsByAppIdAndPlatform_V2(String appId, String platform) {
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId)).addCriteria(Criteria.where("platform").is(platform));
        PointPlatformConfig pointPlatformConfig = this.mongoTemplate.findOne(query, PointPlatformConfig.class);
        if (Objects.isNull(pointPlatformConfig)) {
            return new CsQQOpenIdRes();
        }
        String csQQNumber = pointPlatformConfig.getCsQQNumber();
        String csOpenId = pointPlatformConfig.getCsOpenId();
        CsQQOpenIdRes csQQOpenIdRes = new CsQQOpenIdRes();
        if (StringUtils.isNotBlank(csQQNumber)) {
            csQQOpenIdRes.setCsQQNumber(csQQNumber.split(","));
        }
        if (StringUtils.isNotBlank(csOpenId)) {
            csQQOpenIdRes.setCsOpenId(csOpenId.split(","));
        }
        return csQQOpenIdRes;
    }

    @Override
    public PlatformInfoVO findByAppId(UserPO currentUser, String appId) {
        log.info("【平台信息】获取平台信息 userId ->{} | platform ->{}| appId ->{}", currentUser.getId(), currentUser.getCurrentPlatform(), currentUser.getAppId());
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId)).addCriteria(Criteria.where("platform").is(currentUser.getCurrentPlatform()));
        PointPlatformConfig pointPlatformConfig = this.mongoTemplate.findOne(query, PointPlatformConfig.class);
        if (Objects.isNull(pointPlatformConfig)) {
            return new PlatformInfoVO();
        }
        PlatformInfoVO platformInfo = new PlatformInfoVO();
        platformInfo.setCsImageUrl(pointPlatformConfig.getCsImageUrl());
        return platformInfo;
    }

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sys.open.ai.auth-url:}")
    private String aiAuthUrl;

    @Override
    public AIPointPlatformConfig findAIPlatformConfig() {
        if (StringUtils.isBlank(aiAuthUrl)) {
            throw new BusinessException("ai平台配置接口未配置");
        }
        // 查询AI 小程序appid
        JSONObject body = restTemplate.getForEntity(aiAuthUrl, JSONObject.class).getBody();
        JSONObject data = body.getJSONObject("data");
        String appId = data.getString("appId");
        String authUrl = data.getString("authUrl");
        //查询 配置
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId)).addCriteria(Criteria.where("platform").is("wechat-h5"));
        AIPointPlatformConfig one = this.mongoTemplate.findOne(query, AIPointPlatformConfig.class);
        one.setAuthUrl(authUrl);
        return one;
    }
}
